import request from "../../untils/request";

let isSend = false;
Page({
    data: {
        placeholderContent: '',
        hotList: [],
        searchContent: '',
        searchList: [],//模糊匹配数据
        historyList: []
    },
    onLoad: function (options) {
        this.getInitData();
        this.getSearchHistory()
    },

    async getInitData() {
        let placeholderData = await request('/search/default')
        let hotListData = await request('/search/hot/detail')
        this.setData({
            placeholderContent: placeholderData.data.showKeyword,
            hotList: hotListData.data
        })
    },
    handleInputChange(event) {
        this.setData({
            searchContent: event.detail.value.trim()
        })
        if (isSend) {
            return
        }
        isSend = true;
        this.getSearchList();
        // 节流
        setTimeout(async () => {
            isSend = false
        }, 150)
    },
    async getSearchList() {
        if (!this.data.searchContent) {
            this.setData({
                searchList: []
            })
            return;
        }
        let {searchContent, historyList} = this.data;
        let searchListData = await request('/search', {keywords: searchContent, limit: 10})
        this.setData({
            searchList: searchListData.result.songs
        })
        // 将搜索关键字添加到搜索历史记录中
        if (historyList.indexOf(searchContent) !== -1) {
            historyList.splice(historyList.indexOf(searchContent), 1)
        }
        historyList.unshift(searchContent)

        this.setData({
            historyList
        })
        wx.setStorageSync('searchHistory', historyList)

    },
    // 获取本地历史记录
    getSearchHistory() {
        let historyList = wx.getStorageSync('searchHistory')
        if (historyList) {
            this.setData({
                historyList
            })
        }
    },
    clearSearchContent() {
        this.setData({
            searchContent: '',
            searchList: []
        })
    },
    deleteSearchHistory() {
        wx.showModal({
            content: '确认删除？',
            success: (res) => {
                console.log(res)
                if (res.confirm) {
                    this.setData({
                        historyList: []
                    })
                    wx.removeStorageSync('searchHistory')
                }
            }
        })

    }
});
